#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use std::path::PathBuf;
use tauri::Manager;

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

// 文件系统相关API
#[tauri::command]
async fn select_folder() -> Result<String, String> {
    // 在Tauri中打开文件夹选择对话框
    let dialog = rfd::AsyncFileDialog::new()
        .set_title("选择文件夹")
        .pick_folder()
        .await;
    
    match dialog {
        Some(folder) => {
            match folder.path().to_str() {
                Some(path_str) => Ok(path_str.to_string()),
                None => Err("无法将路径转换为字符串".to_string())
            }
        },
        None => Err("用户取消选择".to_string())
    }
}

#[tauri::command]
async fn get_download_folder() -> Result<String, String> {
    // 获取系统默认下载文件夹
    match dirs::download_dir() {
        Some(download_path) => {
            match download_path.to_str() {
                Some(path_str) => Ok(path_str.to_string()),
                None => Err("无法将下载文件夹路径转换为字符串".to_string())
            }
        },
        None => Err("无法获取下载文件夹路径".to_string())
    }
}

#[tauri::command]
async fn save_file_to_path(file_data: &[u8], file_name: &str, folder_path: &str) -> Result<String, String> {
    let mut file_path = PathBuf::from(folder_path);
    file_path.push(file_name);
    
    match std::fs::write(&file_path, file_data) {
        Ok(_) => {
            match file_path.to_str() {
                Some(path_str) => Ok(path_str.to_string()),
                None => Err("无法将保存路径转换为字符串".to_string())
            }
        },
        Err(e) => Err(format!("保存文件失败: {}", e))
    }
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![greet, select_folder, get_download_folder, save_file_to_path])
        .setup(|app| {
            #[cfg(desktop)]
            {
                let window = app.get_webview_window("main").unwrap();
                let monitor = window.current_monitor().unwrap().unwrap();
                let monitor_size = monitor.size();
                
                // 设置窗口尺寸为屏幕尺寸的80%
                let width = (monitor_size.width as f64 * 0.8) as u32;
                let height = (monitor_size.height as f64 * 0.8) as u32;
                
                // 确保不会超过屏幕尺寸
                let width = width.min(monitor_size.width);
                let height = height.min(monitor_size.height);
                
                // 设置窗口尺寸
                window.set_size(tauri::PhysicalSize::new(width, height)).unwrap();
                
                // 将窗口居中
                window.center().unwrap();
            }
            
            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}